<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
    // 进度条更新
    function progressHandle(e) {
        $('#progress-body progress').attr({
            value: e.loaded,
            max: e.total
        });
        var percent = (e.loaded / e.total * 100).toFixed(2);
        $('#progress-bar').html(percent + '%');
    }

    function uploadSuccess(e) {
        alert('上传成功');
    }
    function uploadFailure(e) {
        alert('上传失败');
    }
    function upload() {
        console.log('上传');
        var formData = new FormData();
        formData.append("file", $("#file")[0].files[0]);
        console.log(formData);
        $.ajax({
            url: "/file/upload",
            type: "POST",
            data: formData,
            processData: false, // 告诉 jQuery 不要去处理发送的数据
            contentType: false, // 告诉 jQuery 不要去设置 Content-Type 请求头
            success: function (data) {
                alert(data);
            },
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                console.log(xhr);
                // xhr.upload 专门用于上传事件监听
                if (xhr.upload) {
                    console.log($.ajaxSettings.xhr().upload)
                    xhr.upload.addEventListener("progress", progressHandle, false);
                    xhr.addEventListener("load", uploadSuccess, false);
                    xhr.addEventListener("error", uploadFailure, false);
                }
                // xhr.upload.onprogress = progressHandle;
                return xhr;
            }
        });
    }
</script>
<body>
    <div class="modal-body form">
        <form id="dialogForm" class="form-horizontal">
            <div class="form-group">
                <label class="control-label">文件: </label>
                <div>
                    <input type="file" id="file" name="file" onchange="upload()" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label">上传进度: </label>
                <div>
                    <div id="progress-body">
                        <progress></progress>
                        <div id="progress-bar">0%</div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>